package flex.cc.single.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;

import flex.cc.PublicUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.core.utils.RequestUtil;
import flex.cc.drive.service.impl.DriverSmsService;
import flex.cc.single.dao.SingleCouponTrackDao;
import flex.cc.single.dao.SingleDriverSynStatusDao;
import flex.cc.single.dao.SingleOrderDao;
import flex.cc.single.dto.entity.SingleCouponTrackEntity;
import flex.cc.single.dto.entity.SingleDriverSynStatusEntity;
import flex.cc.single.dto.entity.SingleOrderEntity;
import flex.cc.single.service.DxVerifyService;
import flex.cc.single.service.SingleDriverSynStatusService;
import flex.cc.single.service.SingleRecordService;
import flex.cc.store.dao.StoreCouponDao;
import flex.cc.store.dto.entity.StoreCouponEntity;

/**
*
* @author R
* 2022年01月14日 13:35:01
* @desc 单项代驾单状态同步实现层
*/
@Service("singleDriverSynStatusService")
@Transactional(rollbackFor = Exception.class)
public class SingleDriverSynStatusServiceImpl implements SingleDriverSynStatusService {
    private static final Logger logger = LoggerFactory.getLogger(SingleDriverSynStatusServiceImpl.class);
    
    @Autowired
    private DxVerifyService dxVerifyService;
    @Autowired
    private SingleOrderDao singleOrderDao;
    @Autowired
    private SingleDriverSynStatusDao singleDriverSynStatusDao;
    @Autowired
    private DriverSmsService driverSmsService;
    @Autowired
    private StoreCouponDao storeCouponDao;
	@Resource
    private SingleRecordService singleRecordService;
	@Autowired
    private SingleCouponTrackDao singleCouponTrackDao;
	
	@Override
	public JSONObject driverSynStatus(Map<String, Object> requestBodyMap,String requestJson) {
		Date requestTime = new Date();
		JSONObject jsonResult = new JSONObject();
		try {
			//预约编号
			String besCode = (String) requestBodyMap.get("besCode");
			if(PublicUtil.isEmpty(besCode)) {
	    		logger.error("预约编号不能为空");
	    		jsonResult.put("resultCode", "ERROR");
	    		jsonResult.put("resultDesc", "预约编号不能为空");
	            return jsonResult;
			}
			//状态
			String status = (String) requestBodyMap.get("status");
			if(PublicUtil.isEmpty(status)) {
	    		logger.error("状态不能为空");
	    		jsonResult.put("resultCode", "ERROR");
	    		jsonResult.put("resultDesc", "状态不能为空");
	            return jsonResult;
			}
			
			//订单编号
			String orderId = (String) requestBodyMap.get("orderId");
			if(PublicUtil.isEmpty(orderId)) {
	    		logger.error("订单编号不能为空");
	    		jsonResult.put("resultCode", "ERROR");
	    		jsonResult.put("resultDesc", "订单编号不能为空");
	            return jsonResult;
			}
			//第三方订单号
			String outTradeNo = (String) requestBodyMap.get("outTradeNo");
			//实际费用
			String actualAmount = (String) requestBodyMap.get("actualAmount");
			//实际公里数
			String actualKm = (String) requestBodyMap.get("actualKm");
			//目的地
			String destination = (String) requestBodyMap.get("destination");
			//取消人
			String canceller = (String) requestBodyMap.get("canceller");
			//取消原因
			String cancelReason = (String) requestBodyMap.get("cancelReason");
			//备注
			String remark = (String) requestBodyMap.get("remark");
			
			
			//根据卡券编码 获取卡券信息
			StoreCouponEntity storeCouponEntity = storeCouponDao.queryByCouponNum(orderId);
			//获取卡券对应的渠道商   渠道商不同 请求不同的核销
			String channel = storeCouponEntity.getChannel();
			
			//国华卡券预约信息查询
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("orderId", orderId);
			SingleOrderEntity singleOrderEntity = singleOrderDao.getOneByParams(params);
			//预约编码
			String orderNo = singleOrderEntity.getOrderNo();
			//卡券编码
			String couponNum = orderId;
			//客户联系电话
			String customerPhone = singleOrderEntity.getTel();
			
			//新增预约状态同步信息
			SingleDriverSynStatusEntity driverSynStatusEntity = new SingleDriverSynStatusEntity();
			driverSynStatusEntity.setOrderNo(orderNo);
			driverSynStatusEntity.setOrderId(orderId);
			driverSynStatusEntity.setBesCode(besCode);
			driverSynStatusEntity.setSource(channel);
			driverSynStatusEntity.setStatus(status);
			driverSynStatusEntity.setOutTradeNo(outTradeNo);
			driverSynStatusEntity.setActualAmount(actualAmount);
			driverSynStatusEntity.setActualKm(actualKm);
			driverSynStatusEntity.setDestination(destination);
			driverSynStatusEntity.setCanceller(canceller);
			driverSynStatusEntity.setCancelReason(cancelReason);
			driverSynStatusEntity.setRemark(remark);
			
			//预约单状态
			String driverOrderStatus = "";
			String driverOrderStatusString = "";
			if(status.equals("1")){//派单成功
				//司机姓名
				String driverName = (String) requestBodyMap.get("driverName");
				//司机电话
				String driverPhone = (String) requestBodyMap.get("driverPhone");
				//司机车牌	
				String carNo = (String) requestBodyMap.get("carNo");
				//车型	
				String vehicleModel = (String) requestBodyMap.get("vehicleModel");
				
				driverSynStatusEntity.setDriverName(driverName);
				driverSynStatusEntity.setDriverPhone(driverPhone);
				driverSynStatusEntity.setCarNo(carNo);
				driverSynStatusEntity.setVehicleModel(vehicleModel);
				
				driverOrderStatusString = "派单成功";
				driverOrderStatus = "02";
				
				//调用短信接口
				Map<String, String> paramMap = new HashMap<String, String>();
				paramMap.put("driverStatus", "001");
				paramMap.put("phoneNumber", customerPhone);
				paramMap.put("driverName", driverName);
				paramMap.put("driverPhone", driverPhone);
				driverSmsService.sendDriverSms(paramMap);
			}else if(status.equals("2")){//服务完成
				driverOrderStatusString = "服务完成";
				driverOrderStatus = "04";
				
				dxVerifyService.asyncVerify(couponNum,orderNo);
			}else if(status.equals("5")){//取消可用服务 
				driverOrderStatusString = "取消可用服务";
				driverOrderStatus = "05";
			}else if(status.equals("6")){//司机已到达
				// 需查询数据库 该服务单 派单成功时 司机电话和司机姓名
				Map<String, Object> paramsMap = new HashMap<String, Object>();
				paramsMap.put("status", "1");
				paramsMap.put("orderNo", orderNo);
				SingleDriverSynStatusEntity driverSynStatusInfo = singleDriverSynStatusDao.getOneByParams(paramsMap);
				String driverPhone = driverSynStatusInfo.getDriverPhone();
				String driverName = driverSynStatusInfo.getDriverName();
				
				//调用短信接口
				Map<String, String> smsParams = new HashMap<String, String>();
				smsParams.put("driverStatus", "002");
				smsParams.put("phoneNumber", customerPhone);
				smsParams.put("driverName", driverName);
				smsParams.put("driverPhone", driverPhone);
				driverSmsService.sendDriverSms(smsParams);
				
				driverOrderStatusString = "司机已到达";
				driverOrderStatus = "03";
			}else if(status.equals("8")){//取消服务完成
				driverOrderStatusString = "取消服务完成";
				driverOrderStatus = "06";
				
				dxVerifyService.asyncVerify(couponNum,orderNo);
			}else if(status.equals("9")){//预约成功	
				driverOrderStatusString = "预约成功";
				driverOrderStatus = "01";
			}else {//其他 不更新代驾服务单状态 只记录轨迹
				driverOrderStatusString = "其他";
			}
			//插入同步状态数据
			driverSynStatusEntity.setCreateTime(new Date());
			driverSynStatusEntity.setCreater("system");
			driverSynStatusEntity.setUpdateTime(new Date());
			driverSynStatusEntity.setUpdater("system");
			driverSynStatusEntity.setIsDelete(0);
			singleDriverSynStatusDao.insert(driverSynStatusEntity);
			
			
			if(PublicUtil.isNotEmpty(driverOrderStatus)){
				//按照状态同步接口返回的状态更新预约服务单
				Map<String, Object> orderParam = new HashMap<String, Object>();
				orderParam.put("status", driverOrderStatus);
				orderParam.put("orderNo", orderNo);
				singleOrderDao.updateByParams(orderParam);
			}
			
			jsonResult.put("resultCode", "SUCCESS");
    		jsonResult.put("resultDesc", "成功,系统处理正常");
			
    		//国华卡券接口日志新增
    		//单项类保存日志：t_single_record
    		JSONObject jsonObj=new JSONObject(requestBodyMap);
			singleRecordService.saveSingleRecord(orderId, orderNo, requestTime, new Date(), "单项代驾类预约单状态同步接口", 
					"0", "成功,系统处理正常,状态："+driverOrderStatusString, requestJson, jsonObj.toString(), null, jsonResult.toString());
			
			LoginAuthDto loginUser = RequestUtil.getLoginUser();
			saveTrack(storeCouponEntity, "2", "单项代驾类预约单状态同步成功，状态："+driverOrderStatusString, "1", loginUser.getUserCode());
	    	
	    	return jsonResult;
		}catch (Exception e) {
			logger.info("预约单状态同步接口异常"+e.getMessage());
			jsonResult.put("resultCode", "ERROR");
    		jsonResult.put("resultDesc", "预约单状态同步接口异常");
            return jsonResult;
		}
	}
	
	/**
	 * 新增卡券使用轨迹
	 * @param couponEntity  卡券信息
	 * @param trackType 轨迹类型：0-车服内部，1-与上游交互，2-与下游交互，3-与商户端交互
	 * @param trackDesc 轨迹描述
	 * @param result 接口请求结果：0-失败，1-成功
	 * @param creater
	 */
	 private void saveTrack(StoreCouponEntity couponEntity, String trackType, String trackDesc, String result, String creater){
		 Date d = new Date();
		 SingleCouponTrackEntity vo = new SingleCouponTrackEntity(couponEntity.getId(),couponEntity.getCouponNum(),
				 trackType,trackDesc,couponEntity.getStatus(),result);
		 vo.setIsDelete(0);
		 vo.setCreateTime(d);
		 vo.setCreater(creater);
		 vo.setUpdateTime(d);
		 vo.setUpdater(creater);
		 singleCouponTrackDao.insert(vo);	        
	 }
}
